package cn.etcweb.bait.baitframe.auth.service;

import cn.etcweb.bait.baitframe.auth.bean.SysUser;
import cn.etcweb.bait.baitframe.auth.bean.User;
import cn.etcweb.bait.baitframe.auth.integration.IntegrationAuthentication;
import cn.etcweb.bait.baitframe.auth.integration.IntegrationAuthenticationContext;
import cn.etcweb.bait.baitframe.auth.integration.authenticator.IntegrationAuthenticator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 集成认证用户服务
 */
@Service
public class IntegrationUserDetailsService implements UserDetailsService{
    private List<IntegrationAuthenticator> authenticators;

    @Autowired(required = false)
    public void setIntegrationAuthenticators(List<IntegrationAuthenticator> authenticators) {
        this.authenticators = authenticators;
    }

    @Override
    public User loadUserByUsername(String username) throws UsernameNotFoundException {
        IntegrationAuthentication integrationAuthentication = IntegrationAuthenticationContext.get();
        //判断是否是集成登录
        if (integrationAuthentication == null) {
            integrationAuthentication = new IntegrationAuthentication();
        }
        integrationAuthentication.setUsername(username);
        SysUser sysUser=this.authenticate(integrationAuthentication);
        if (sysUser==null){
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        User user=new User();
        BeanUtils.copyProperties(sysUser,user);
        this.setAuthorize(user);
        return user;
    }

    /**
     * 设置授权信息 获取用户权限信息部分内容未完成
     *
     * @param user
     */
    public void setAuthorize(User user) {
        //Authorize authorize = this.upmClient.getAuthorize(user.getId());
        //user.setRoles(authorize.getRoles());
        //user.setResources(authorize.getResources());
    }

    private SysUser authenticate(IntegrationAuthentication integrationAuthentication) {
        if (this.authenticators != null) {
            for (IntegrationAuthenticator authenticator : authenticators) {
                if (authenticator.support(integrationAuthentication)) {
                    return authenticator.authenticate(integrationAuthentication);
                }
            }
        }
        return null;
    }
}
